extends CharacterBody2D

class_name PlayerScript

const SPEED = 80.0
const JUMP_VELOCITY = -240.0
const HIT_VELOCITY_Y = -100.0
const HIT_VELOCITY_X = 70
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var gravityScale = 0.5
var friction = 300
var airResist = 150
var acceleration = 300
@onready var animations:AnimatedSprite2D = $AnimatedSprite2D
@onready var animationPlayer = $AnimationPlayer

var inputDirection = 0

var stateMachine:StateMachine
var currentWeapon

var level = 1
var exp = 0
var health = 5
var damage = 1
var hittable = true
var enemyAttacker


func _ready():
	add_to_group("Player")
	stateMachine = get_node("StateMachine") as StateMachine
	stateMachine.changeState("StateNormal", self)
	GlobalSignal.playerHealthChanged.emit()
	

func _physics_process(delta):
	stateMachine.physicsProcess(delta, self)
	

func _process(delta):
	(stateMachine as StateMachine).process(delta, self)


func setPosition(targetPosition):
	global_position = targetPosition
	
	
func changeWeapon(newWeapon):
	if currentWeapon:
		# drop the currentWeapon
		Global.createLoot(GlobalUtils.strFirstChar2Lower(currentWeapon), global_position, get_tree().current_scene)
	
	currentWeapon = newWeapon


func _on_iron_rod_hit_area_body_entered(body):
	if body.is_in_group("Enemy"):
		(body as Enemy01).onHit(self)


func _on_club_hit_area_body_entered(body):
	_on_iron_rod_hit_area_body_entered(body)
		

func onHit(attacker):
	if not hittable: 
		return
	hittable = false
	
	Global.createHitEffect(global_position + Vector2(0, -8) + GlobalUtils.vector2RandomRange(5, 5), get_tree().current_scene)
	
	health -= attacker.damage
	enemyAttacker = attacker
	GlobalSignal.playerHealthChanged.emit()
	GlobalSignal.frameFreeze.emit()
	stateMachine.changeState("StateHit", self)
	

func setHitFlashWhite():
	animations.material.set_shader_parameter("active", true)
	

func setHitFlashOrigin():
	animations.material.set_shader_parameter("active", false)
	
	
func gainExp(v):
	exp += v
	if exp >= Global.levelUpExpConfig[str(level+1)]:
		level += 1
		health = Global.levelsConfig[str(level)]["health"]
		damage = Global.levelsConfig[str(level)]["damage"]
		GlobalSignal.playerHealthChanged.emit()
		

